package lincen.javase.util.time.taskutil;

import java.util.Calendar;
import java.util.Timer;

/**
 * 任务中心, 这里存放了各种各样的任务, 可以通过各种addTask方法向这个任务中心的实例中添加任务
 * 
 * @author 张腾
 * 
 */
public class TaskCenter implements ITaskCenter {

	/** 一分钟的毫秒数 */
	public static final long MILES_ONE_MIN = 60 * 1000;
	
	/** 一小时的毫秒数 */
	public static final long MILES_ONE_HOUR = 60 * MILES_ONE_MIN;
	
	/** 一天的毫秒数 */
	public static final long MILES_ONE_DAY = 24 * MILES_ONE_HOUR;
	
	private static ITaskCenter INSTANCE;
	
	private TaskCenter(){}
	
	public static ITaskCenter getInstance() {
		if(INSTANCE == null) {
			INSTANCE = new TaskCenter();
		}
		return INSTANCE;
	}
	
	private Timer timer = new Timer();
	
	@Override
	public void loopFrom( String start, long period, TaskSafety task ) {
		timer.scheduleAtFixedRate(task, longFormat(start), period);
	}

	@Override
	public void loopEveryDay(String timeAtEveryDay, TaskSafety task) {
		timer.scheduleAtFixedRate(task, longFormat(timeAtEveryDay), MILES_ONE_DAY);
	}

	@Override
	public void loopNextClock(long period, TaskSafety task) {
		timer.scheduleAtFixedRate(task, nextHour(), period);
	}

	/**
	 * 获得当前时间下个小时整点时间
	 * @return
	 */
	public static final long nextHour(){
		Calendar c = Calendar.getInstance();
		long min = (60 - c.get(Calendar.MINUTE - 1)) * MILES_ONE_MIN;
		long sec = (60 - c.get(Calendar.SECOND)) * 1000;
		return min + sec;
	}

	/**
	 * 把一个格式为 "00:00"的字符串转换为long类型<br/>
	 * 如当前时间是9:00 传入时间是9:01返回1*60*1000 = 60000
	 * 
	 * @param string
	 * @return
	 */
	public static final long longFormat(String string) {

		// 拿到传入字符串的小时和分钟
		long nextHour = Long.parseLong(string.substring(0, 2)) * MILES_ONE_HOUR;
		long nextMin = Long.parseLong(string.substring(3, 5)) * MILES_ONE_MIN;

		// 当前小时和分钟
		Calendar c = Calendar.getInstance();
		long nowHour = c.get(Calendar.HOUR_OF_DAY) * MILES_ONE_HOUR;
		long nowMin = c.get(Calendar.MINUTE) * MILES_ONE_MIN;
		long nowSec = c.get(Calendar.SECOND) * 1000;
		
		// 传入的时间减去当前时间
		long time = nextHour - nowHour + nextMin - nowMin - nowSec;

		if (time < 0) {
			time += MILES_ONE_DAY;// 加一天时间
		}

		return time;
	}

	@Override
	public void loop(long period, long delay, TaskSafety task) {
		timer.scheduleAtFixedRate(task, delay, period);
	}


}
